// pages/couponCenter/couponCenter.js
const couponService = require('../../../api/couponService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStoreInfo: {
      storeId: '',
      storeName: '未获取到门店信息'
    },
    couponList: [],
    page: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.storeInfo) {
      this.setData({
        currentStoreInfo: {
          storeId: app.globalData.storeInfo.id,
          storeName: app.globalData.storeInfo.name
        }
      })
      this.getCouponList(1, 0)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    // this.getCouponList(1, 0)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // 获取券列表
  getCouponList: function(page, pageSize) {
    wx.showLoading({
      title: '加载中',
    })
    const that = this
    let storeId = that.data.currentStoreInfo.storeId
    let postData = {
      page: page,
      pageSize: pageSize,
      storeIdEquals: storeId
    }
    let couponList = [
      [],
      []
    ]
    couponList[0] = couponService.getCouponActivitiesByFilter(postData).then(res => {
      let tempList = []
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          if (item.status === 'COMMIT') {
            let tempItem = {
              ...item,
              isExternal: false
            }
            tempList.push(tempItem)
          }
        })
      }
      return tempList
    })
    couponList[1] = couponService.getExternalCouponActivities().then(res => {
      let tempList = []
      if (res && res.length > 0) {
        res.forEach(item => {
          if (item.status === 'COMMIT') {
            let tempItem = {
              ...item,
              isExternal: true
            }
            tempList.push(tempItem)
          }
        })
      }
      return tempList
    }).catch(e => {
      return []
    })
    Promise.all(couponList).then(res => {
      console.log(res)
      let tempList = res[0].concat(res[1])
      let newTempList = []
      tempList.forEach(ele => {
        if (ele.rate) {
          ele = {
            ...ele,
            rate: (ele.rate * 10).toFixed(1)
          }
        }
        newTempList.push(ele)
      })
      console.log(newTempList)
      wx.hideLoading()
      that.setData({
        couponList: newTempList
      })
    })
  },
  // 前往券详情页面
  toCouponDetails: function(val) {
    const isExternal = val.currentTarget.dataset.external
    if (!isExternal) {
      wx.navigateTo({
        url: '../couponDetails/couponDetails?couponActivityId=' + val.currentTarget.dataset.couponid + '&type=assign&isExternal=' + isExternal
      })
    } else {
      // 外部券无详情不跳转
      wx.showToast({
        title: '该券不能查看',
        icon: 'none',
        duration: 1500
      })
    }
  },
  // 领券
  handleCoupon: function(val) {
    const that = this
    const couponId = val.currentTarget.dataset.couponid
    const couponList = that.data.couponList
    var currentCoupon = null
    couponList.forEach(item => {
      if (couponId === item.id) {
        currentCoupon = item
      }
    })
    if (currentCoupon.service === 'HD') {
      // 外部券 HD
      couponService.createCouponOrder(currentCoupon.dlyCouponActivityId).then(res => {
        console.log(res)
        if (res.status === 'ACQUIRE') {
          wx.showToast({
            title: '领券成功',
            icon: 'none',
            duration: 2000
          })
        } else if (res.status === 'CREATED') {
          let postData = {
            orderId: res.id,
            // payMethod: 'SWIFTPASS'
            payMethod: 'WX_MINI_APP'
          }
          couponService.getCouponPaySign(postData).then(res => {
            console.log(res)
            var resData = JSON.parse(res);
            var sign = JSON.parse(resData.sign)
            console.log(sign)
            let tempPackage = "";
            if (postData.payMethod === 'WX_MINI_APP') {
              tempPackage = sign.packageValue;
            } else if (postData.payMethod === 'SWIFTPASS') {
              tempPackage = sign.package;
            }

            wx.requestPayment({
              'timeStamp': sign.timeStamp,
              'nonceStr': sign.nonceStr,
              'package': tempPackage,
              'signType': sign.signType,
              'paySign': sign.paySign,
              'success': function(res) {
                wx.showToast({
                  title: '领券成功',
                  icon: 'none',
                  duration: 2000
                })
              },
              'fail': function(res) {
                console.log('支付失败')
                console.log(res)
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })

          }).catch(err => {
            if (err.code === 1) {
              wx.showToast({
                title: '领券失败',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else {
          wx.showToast({
            title: res.acquireFailedReason,
            icon: 'none',
            duration: 2000
          })
        }
      }).catch(e => {
        console.log(e)
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      // 内部券
      if (currentCoupon.balance > 0) {
        let postData = {
          activityId: couponId
        }
        couponService.assign(postData).then(res => {
          console.log(res)
          wx.showToast({
            title: '领券成功',
            icon: 'none',
            duration: 2000
          })
        }).catch(e => {
          console.log(e)
          if (e.code === 17005) {
            wx.showToast({
              title: '券活动指定的有效期已经过期，不能领取~',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.showToast({
          title: '券已经被抢光了哦~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  /**
   * 跳转到门店选择页
   */
  toSelectStore: function() {
    wx.navigateTo({
      url: '../../selectStore/selectStore',
    })
  }
})